import store from '@/store'
import router from '@/router'
import axios from 'axios'
import { Message } from 'element-ui'
const service = axios.create({
  // 配置环境变量
  baseURL: 'http://forest.kmdsoft.net',

  timeout: 5000
})
const tokenTime = 7200

function isCheckTimeOut() {
  const time2 = Date.now()
  const timeStemp = (time2 - store.getters.ihrmTime) / 1000
  return timeStemp > tokenTime
}

// 请求拦截器

service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      // console.log(store.getters.token)
      // token超时主动介入
      if (isCheckTimeOut()) {
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject(new Error('token超时，请重新登录'))
      }
      config.headers.token = `${store.getters.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data } = response.data
    // if (success) {
    //   return data
    // } else {
    //   return Promise.reject(new Error(message))
    // }
    return data
  },
  (error) => {
    if (error && error.response && error.response.status === 401) {
      store.dispatch('user/logout')
      router.push('/login')
      Message.error(error.response.data.message || 'token失效，请重新登录')
    } else {
      Message.error(error.message || '后端服务器报错')
    }
    return Promise.reject(error)
  }
)
export default service
